package com.lituoxy.dialer.thread;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;

import com.lituoxy.dialer.DialerApplication;
import com.lituoxy.dialer.util.UIUtil;
import com.huawei.rcs.caasomp.CaasOmpCfg;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 作者：许航晨 on 2017/7/7 14:48
 * 邮箱：948340983@qq.com
 */

public class HttpRequestDispatch extends Thread {
    private String mCalleeNumber;
    private Context mAction = null;
    private Handler mHandler = null;
    private String mUrl = null;
    private int mHandlerIndex = 0;
    public static String app_key = "5qcg1AxEKNcUGyjP2J8Sun63SI80";

    public HttpRequestDispatch(Context action, Handler handler, String calleeNumber) {
        mAction = action;
        mUrl = "https://117.78.29.66:10443" + "/rest/httpsessions/click2Call/v2.0?app_key=" + app_key + "&access_token=" + ((DialerApplication) DialerApplication.getContext()).getToKey() + "&format=json";
        mHandler = handler;
        mCalleeNumber = calleeNumber;
    }

    public void run() {
        if (((DialerApplication) DialerApplication.getContext()).getToKey() == null) {
            Looper.prepare();
            Toast.makeText(mAction, "您拨打的电话正忙请稍后再拨......", Toast.LENGTH_SHORT).show();
            Looper.loop();
            return;
        }
        Call();
    }

    private void Call() {
        try {
            if (mUrl == null) {
                //mAction.alertToast("请求地址不能为空");
                return;
            }
            HttpClient httpsClient = HttpClientInstance.getHttpsClientIns();
            HttpPost httpRequest = new HttpPost(mUrl);
            httpRequest.setHeader("connection", "Keep-Alive");
            httpRequest.setHeader("Accept", "*/*");
            httpRequest.setHeader("Authorization", "CaaS2.0?");
            httpRequest.setHeader("Content-Type", "application/json");
            String json1 = "{\"bindNbr\":\"+8678880003440\",\"displayNbr\":\"9506593\",\"callerNbr\":\"" + CaasOmpCfg.getString(CaasOmpCfg.EN_OMP_CFG_USER_NAME) + "\",\"calleeNbr\":\"" + mCalleeNumber + "\",\"displayCalleeNbr\":\"9506593\",\"lastMinToUE\":\"both\",\"calleeMedia\":\"all\",\"recordFlag\":\"false\",\"userData\":\"CaaS Hosting Test\",\"maxduration\":30}";
            httpRequest.setEntity(new StringEntity(json1.toString(), "UTF-8"));
            //httpRequest.setEntity(new UrlEncodedFormEntity(mParams, HTTP.UTF_8));
            HttpResponse response = httpsClient.execute(httpRequest);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            JSONObject object = new JSONObject(buffer.toString());
            //{"resultcode":"1010004","resultdesc":"Invalid Token"}
            String resultdesc = object.getString("resultdesc");
            String resultcode = object.getString("resultcode");

            if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
                if ("Invalid Token".equals(resultdesc)) {//token 过期
                    fastlogin();
                } else if ("1010003".equals(resultcode)) {
                    fastlogin();
                } else {
                    UIUtil.cancelProgressDialog();
                    Looper.prepare();
                    Toast.makeText(mAction, "拨号失败 请检查号码是否正确", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
                //throw new Exception("ResponseCode:" + response.getStatusLine().getStatusCode());
            }


            if (mHandler != null) {
                sendResultBack(buffer.toString());
            }
        } catch (Exception e) {
            UIUtil.cancelProgressDialog();
            e.printStackTrace();
            Looper.prepare();
            Toast.makeText(mAction, "网络错误 " + e.toString(), Toast.LENGTH_SHORT).show();
            Looper.loop();
        }
    }

    private void fastlogin() {
        try {
            String url = "https://117.78.29.66:10443" + "/rest/fastlogin/v1.0" + "?app_key=" + app_key + "&username=xianlituo&format=json";
            HttpClient httpsClient = HttpClientInstance.getHttpsClientIns();
            HttpPost httpRequest = new HttpPost(url);
            httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            httpRequest.setHeader("connection", "Keep-Alive");
            httpRequest.setHeader("Accept", "*/*");
            httpRequest.setHeader("Authorization", "Test2.0?x");
            HttpResponse response1 = httpsClient.execute(httpRequest);
            if (response1.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
                throw new Exception("ResponseCode:" + response1.getStatusLine().getStatusCode());
            }

            BufferedReader reader = null;

            reader = new BufferedReader(new InputStreamReader(response1.getEntity().getContent()));
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            JSONObject object = new JSONObject(buffer.toString());
            //{"access_token":"MTUwMDQzNjY0MDUxODE5NTQyMTcyNzUzNDUyNzUwMjUyNzQzOTY3NDI3MjkzQHRydXN0b21wMjQxLmh1YXdlaWNhYXMuY29t","refresh_token":"MTUwMDQzNjY0MDUxODU1ODA0NTQzNzE3Nzc1Mjk4NDU1MjE5MzkwNDYxNDE5QHRydXN0b21wMjQxLmh1YXdlaWNhYXMuY29t","expires_in":"172800","openCapability":"false","resultcode":"0","resultdesc":"Succeed"}
            String access_token = object.getString("access_token");
            boolean ifSetToken = false;
            ifSetToken = setToken(access_token);//进行重设token
            while (!ifSetToken) {
                try {
                    Thread.sleep(1000);
                    ifSetToken = setToken(access_token);//进行重设token
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            mUrl = "https://117.78.29.66:10443" + "/sandbox/rest/httpsessions/click2Call/v2.0?app_key=" + app_key + "&access_token=" + access_token + "&format=json";
            Call();//进行打电话
            // sendResultBack(buffer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean setToken(String access_token) {
        /*http://localhost/lituo_api/public/accesstoken/add2
        POST
        {
            "key":  "kjasdhfgk34rt89790yhiklsdhnf897867vnnnn",
                "access_token":  "MTQ5OTY4MDY3NDQ0NDMwMzkzNDgwMTk2OTg3MDkxMzcxODMzNDY3OTUzMTg0QHRydXN0b21wMjQxLmh1YXdlaWNhYXMuY29t"
        }*/
        RequestBody formBody = new FormBody.Builder()
                .add("key", "kjasdhfgk34rt89790yhiklsdhnf897867vnnnn")
                .add("access_token", access_token)
                .build();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://120.25.227.239:8060/accesstoken/add2").post(formBody)
                .build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String json = response.body().string();
                JSONObject object = new JSONObject(json);
                String info = object.getString("info");
                if ("成功".equals(info)) {//成功
                    //object = object.getJSONObject("data");
                    //access_token = object.getString("access_token");
                    return true;
                }

            } else {
                throw new IOException("Unexpected code " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
        //return access_token;
    }

    private void sendResultBack(String result) {
        Message message = mHandler.obtainMessage();
        message.what = mHandlerIndex;
        message.obj = result;
        mHandler.sendMessage(message);
    }

}
